<template>
  <ElDialog v-model="dialogVisible" :show-close="false" :scroll="true" :width="500">
    <template #header>
      <h3 class="titleClass">批量导入</h3>
    </template>
    <ContentWrap>
      <div style="display: flex; align-items: center">
        <div>是否仅更新已存在数据:</div>
        <el-radio-group v-model="dataParams.updateSupport" class="ml-4">
          <el-radio :label="true" size="large" disabled>是</el-radio>
          <el-radio :label="false" size="large">否</el-radio>
        </el-radio-group>
      </div>
    </ContentWrap>
    <p
      >1.还没创建过导入数据文件
      <span style="color: blue; cursor: pointer" @click="downloadTemplate">下载模板>>></span></p
    >
    <p>2.已创建好导入数据文件，直接导入</p>
    <p>3.导入文件为.xls或.xlsx的excel文件，最多支持4M，一次导入不超过1000条记录。</p>
    <el-upload
      v-loading="formLoading"
      ref="uploadRef"
      v-model:file-list="fileList"
      :action="uploadUrl + '?updateSupport=' + dataParams.updateSupport"
      :auto-upload="true"
      :disabled="formLoading"
      :headers="uploadHeaders"
      :limit="1"
      :on-error="submitFormError"
      :on-exceed="handleExceed"
      :on-success="submitFormSuccess"
      :before-upload="beforeUpload"
      accept=".xlsx, .xls"
      drag
    >
      <el-button type="primary"><Icon icon="ep:upload-filled" />选取文件</el-button>
    </el-upload>
    <template #footer>
      <el-button @click="close">取 消</el-button>
    </template>
  </ElDialog>
</template>

<script lang="ts" setup>
  import { ref } from 'vue'
  import request from '@/config/axios'
  import download from '@/utils/download'
  import { getAccessToken, getTenantId } from '@/utils/auth'
  import type { UploadProps, UploadRawFile } from 'element-plus'

  const dialogVisible = ref(false) // 弹窗的是否展示
  const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
  const uploadHeaders = ref({
    Authorization: 'Bearer ' + getAccessToken(),
    'tenant-id': getTenantId()
  }) // 上传 Header 头
  const message = useMessage() // 消息弹窗
  const dataParams = reactive({
    //选中
    updateSupport: false
  })
  const fileList = ref([])
  const drawingList = ref([])
  /**下载模板 */
  const downloadTemplate = async () => {
    formLoading.value = true
    let data = await request.download({ url: downloadUrl.value })
    download.excel(data, '模板文件')
    formLoading.value = false
  }

  /** 打开弹窗 */
  const downloadUrl = ref('') // 导出模板方法
  const uploadUrl = ref('') //上传方法
  const open = async (downCusUrl: any, uploadCusUrl: any) => {
    downloadUrl.value = downCusUrl
    uploadUrl.value = `${import.meta.env.VITE_BASE_URL}/admin-api${uploadCusUrl}`
    console.log(uploadUrl.value)
    dialogVisible.value = true
  }
  defineExpose({ open }) // 提供 open 方法，用于打开弹窗
  /**关闭 */
  const emit = defineEmits(['refresh'])
  const close = () => {
    fileList.value = []
    dataParams.updateSupport = false
    console.log(fileList.value)
    dialogVisible.value = false
    emit('refresh', drawingList.value)
  }

  /**上传前 */
  // 文件上传之前判断
  const beforeUpload: UploadProps['beforeUpload'] = (file: UploadRawFile) => {
    const isLimit = file.size < 4 * 1024 * 1024
    if (!isLimit) {
      message.error(`上传文件大小不能超过4MB!`)
      return false
    }
    formLoading.value = true
    //message.success('正在上传文件，请稍候...')
  }

  /** 上传错误提示 */
  const submitFormError = (): void => {
    message.error('上传失败，请您重新上传！')
    formLoading.value = false
  }

  /** 文件数超出提示 */
  const handleExceed = (): void => {
    message.error('最多只能上传一个文件！')
    formLoading.value = false
  }

  const submitFormSuccess = (response: any) => {
    console.log(response)
    if (response.code !== 0) {
      message.error(response.msg)
      formLoading.value = false
      return
    }

    // 拼接提示语
    const data = response.data
    if (data.length > 0) {
      message.success('上传成功')
      formLoading.value = false
      dialogVisible.value = false
      drawingList.value = data
      emit('refresh', drawingList.value)
      fileList.value = []
    } else {
      message.success('上传失败')
      drawingList.value = data
      formLoading.value = false
    }
  }
</script>
<style lang="scss" scoped>
</style>
